import $H from '../../utils/request.js';
import io from "../../common/uni-socket.io.js"
export default {
	state: {
		user: false,
		socket: null,
		token: ""
	},
	actions: {
		connectSocket({
			state,
			dispatch
		}) {
			const socket1 = io("http://192.168.0.106:7001/", {
				query: {},
				transports: ['websocket'],
				timeout: 5000
			})
			let onlineEvent = (e) => {
				uni.$emit("live", {
					type: "online",
					data: e
				})
			}
			let commentEvent = (e) => {
				uni.$emit("live", {
					type: "comment",
					data: e
				})
			}
			let giftEvent = (e) => {
				uni.$emit("live", {
					type: "gift",
					data: e
				})
			}
			//监听连接打开
			socket1.on('connect', () => {
				console.log("已连接")
				state.socket = socket1
				socket1.emit("test", {
					ceshi: "123456"
				})
				socket1.on(socket1.id, (e) => {
					console.log(e, "e")
					let d = e.data
					if (d.action === 'error') {
						let msg = d.payload
						return uni.showToast({
							title: msg,
							icon: 'none'
						})

					}
				})
				socket1.on('online', onlineEvent)
				socket1.on('comment', commentEvent)
								socket1.on('gift', giftEvent)
			})
			//移除监听事件方法
			const removeListener = () => {
				socket1.removeListener('online', onlineEvent)
				socket1.removeListener('comment', commentEvent)
								socket1.removeListener('gift', giftEvent)

			}
			//监听连接错误
			socket1.on('error', (e) => {
				console.log(e, "e")
				removeListener()
				state.socket = null
				console.log("连接错误")
			})
			//监听连接失败
			socket1.on('disconnect', () => {
				state.socket = null
				removeListener()
				console.log("监听失败")
			})

		},
		login({
			state,
			dispatch
		}, user) {
			console.log(user, "user")
			state.user = user
			state.token = user.token
			// state.chat=new chat({url:"ws://127.0.0.1:7001/ws?token=" + state.user.token})
			console.log(state.user, "useruser")
			uni.setStorageSync("token", user.token);
			uni.setStorageSync("user", JSON.stringify(user));
			uni.setStorageSync("user_id", user.id)
			dispatch('initlogin')
		},
		logout({
			state
		}) {
			$H.post("user/logout", {}, {
				token: true
			}).then(res => {
				uni.showToast({
					title: res.msg
				})
				uni.removeStorage({
					key: "token"
				})
				// uni.removeStorage("token")
				// uni.clearStorageSync();
				console.log(state.chat, "123")
				if (state.chat) {
					console.log(state.chat)

					state.chat.getName()
					console.log(1233);
					state.chat = null
				}

				uni.navigateTo({
					url: "/pages/login/login"
				})

			})
		},
		initlogin({
			state,
			dispatch
		}) {
			if (uni.getStorageSync("user")) {
				state.user = JSON.parse(uni.getStorageSync("user"))
				state.token = state.user.token
			}
		}

	}
}
